<template>
    <!-- 编辑属性分类 -->
    <div>
        <el-dialog :model-value="dialogFormVisible" :title="title + '类型'" width="30%" @close="closeFn">
            <el-form :model="form" :rules="rules" ref="ruleFormRef">
                <el-form-item label="类型名称" prop="name" label-width="120px">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelType">取消</el-button>
                    <el-button type="primary" @click="confirmType">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import * as http from '@/request/http'
import { ElMessage, FormInstance } from 'element-plus';

const ruleFormRef = ref<FormInstance>()

const props = withDefaults(defineProps<{ dialogFormVisible: boolean, title: string, id: number }>(), {
    dialogFormVisible: false, title: '添加', id: 0
})
//类型名称参数
const form = reactive({
    name: ''
})
//类型名称表单校验
const rules = reactive({
    name: [
        { required: true, message: '请输入类型名称', trigger: 'blur' }
    ],
})

const emit = defineEmits<{
    (e: 'cancel'): void
    (e: 'confirm'): void
}>()

const cancelType = () => {

    emit('cancel')
}
//添加属性分类
const AddType = () => {
    http.productAttr.productAttrCreate(form.name).then(res => {
        if (res.code == 200) {
            ElMessage.success('添加成功')
            ruleFormRef.value?.resetFields()
            emit('confirm')
        }
    })
}
//修改属性分类
const EditType = () => {
    http.productAttr.productAttrUpdate(props.id, form.name).then(_res => {
        ElMessage.success('修改成功')
        ruleFormRef.value?.resetFields()
        emit('confirm')
    })
}
const confirmType = () => {
    ruleFormRef.value?.validate((valid) => {
        if (valid) {
            if (props.id === 0) {
                AddType()
            } else {
                EditType()
            }
        } else {
            return false
        }
    })

}
const closeFn = () => {
    emit('cancel')
}

watch(
    () => props.id,
    () => {
        if (props.id != 0) {
            http.productAttr.productAttrCategoryId(props.id).then(res => {
                // form.name = res.data.name
                Object.assign(form, res.data)
            })
        } else {
            ruleFormRef.value?.resetFields()
        }
    }
)
</script>

<style scoped></style>